package com.cloud.order.converter;

import com.cloud.order.dto.OrderCreateDto;
import com.cloud.order.entity.OrderDetail;
import com.cloud.order.exception.OrderException;
import com.cloud.order.from.OrderForm;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * describe:
 *
 * @author zhanghaixuan
 * @date 2018/09/11
 **/
@Slf4j
public class OrderForm2OrderDTOConverter {

    public static OrderCreateDto convert(OrderForm orderForm) {
        Gson gson = new Gson();
        OrderCreateDto orderDTO = new OrderCreateDto();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenId());

        List<OrderDetail> orderDetailList = new ArrayList<>();
        try {
            orderDetailList = gson.fromJson(orderForm.getItemId(),
                    new TypeToken<List<OrderDetail>>() {
                    }.getType());
        } catch (Exception e) {
            log.error("【json转换】错误, string={}", orderForm.getItemId());
            throw new OrderException("转换错误");
        }
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}

